﻿using System.Text.Json;
using AutoMapper;
using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;

namespace DataManageSystem.Services
{
    public class OfficeDevicesServices
    {
        private readonly ApplicationDbContext _context;
        private readonly IMapper _mapper;

        public OfficeDevicesServices(ApplicationDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public void Add(OfficeDeviceDevDto officeDeviceDevDto)
        {
            var officeDevice = _mapper.Map<OfficeDevices>(officeDeviceDevDto);

            // 获取现有最大 ID
            var lastId = _context.OfficeDevices
                .Where(d => d.Id.StartsWith("TJ"))
                .OrderByDescending(d => d.Id)
                .Select(d => d.Id)
                .FirstOrDefault();

            int nextNumber = 1;

            if (!string.IsNullOrEmpty(lastId) && lastId.Length > 2)
            {
                var numberPart = lastId.Substring(2); // 去掉 "TJ"，取后面的数字
                if (int.TryParse(numberPart, out int currentNumber))
                {
                    nextNumber = currentNumber + 1;
                }
            }

            officeDevice.Id = $"TJ{nextNumber.ToString("D3")}";  // D3 = 补零到3位
            officeDevice.CreateTime = DateTime.Now;
            officeDevice.UpdateTime = DateTime.Now;

            _context.OfficeDevices.Add(officeDevice);
            _context.SaveChanges();
        }




        /// <summary>
        /// 分页查询办公设备
        /// </summary>
        public Result SelectByPage(int page, int size, string? deviceName, string? type,string? deviceUsePersonName,string? deviceCode)
        {
            var query = _context.OfficeDevices.AsQueryable();

            if (!string.IsNullOrEmpty(deviceName))
            {
                query = query.Where(m => m.DeviceName.Contains(deviceName));
            }

            if (!string.IsNullOrEmpty(type))
            {
                query = query.Where(m => m.DeviceType.Contains(type));
            }

            if (!string.IsNullOrEmpty(deviceUsePersonName))
            {
                query = query.Where(m => m.DeviceUsePerson.Contains(deviceUsePersonName));
            }

            if (!string.IsNullOrEmpty(deviceCode))
            {
                query = query.Where(m => m.DeviceCode.Contains(deviceCode));
            }

            int total = query.Count();
            var officeDevices = query
                .OrderByDescending(m => m.Id)
                .Skip((page - 1) * size)
                .Take(size)
                .ToList();

            return Result.Success(officeDevices, total);
        }

        /// <summary>
        /// 更新办公设备信息
        /// </summary>
        public void Update(OfficeDeviceDevDto officeDeviceDevDto)
        {
            if (officeDeviceDevDto == null || string.IsNullOrEmpty(officeDeviceDevDto.Id))
            {
                throw new ServiceException("无效的设备信息");
            }

            //if(!string.IsNullOrEmpty(officeDeviceDevDto.DeviceUsePerson) && officeDeviceDevDto.DeviceStatus == "未分配")
            //{
            //    officeDeviceDevDto.DeviceStatus = "已分配";
            //}

            //if (string.IsNullOrEmpty(officeDeviceDevDto.DeviceUsePerson) && officeDeviceDevDto.DeviceStatus == "已分配")
            //{
            //    officeDeviceDevDto.DeviceStatus = "未分配";
            //}

            var existOfficeDevice = _context.OfficeDevices.FirstOrDefault(m =>
                m.Id == officeDeviceDevDto.Id
            );
            if (existOfficeDevice == null)
            {
                throw new ServiceException("设备不存在");
            }

            _mapper.Map(officeDeviceDevDto, existOfficeDevice);
            existOfficeDevice.UpdateTime = DateTime.Now;
            _context.OfficeDevices.Update(existOfficeDevice);
            _context.SaveChanges();
        }

        public void Delete(string id)
        {
            var officeDevice = _context.OfficeDevices.FirstOrDefault(m => m.Id == id);
            if (officeDevice != null)
            {
                _context.OfficeDevices.Remove(officeDevice);
                _context.SaveChanges();
            }
            else
            {
                throw new ServiceException("设备不存在");
            }
        }

        /// <summary>
        /// 生成设备信息json
        /// </summary>
        /// <param name="guid"></param>
        /// <exception cref="ServiceException"></exception>
        public OfficeDevices GetDeviceInfo(string guid)
        {
            var officeDevice = _context.OfficeDevices.FirstOrDefault(m => m.Id == guid);
            if(officeDevice == null)
            {
                throw new ServiceException("设备不存在");
            }
            else
            {
                return officeDevice;
            }
 
        }
    }
}
